package com.jsbs.iam.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.jsbs.iam.auth.constant.Constants;
import com.jsbs.iam.auth.dto.*;
import com.jsbs.iam.auth.param.IamQueryStaticUserGroupParam;
import com.jsbs.iam.auth.param.IamQueryStaticUserGroupUsersParam;
import com.jsbs.iam.auth.param.IamStaticUserGroupDeleteParam;
import com.jsbs.iam.auth.service.IamRoleManagerService;
import com.jsbs.iam.auth.service.IamStaticUserGroupManagerService;
import com.jsbs.iam.auth.vo.*;
import com.jsbs.iam.common.core.dto.Result;
import com.jsbs.iam.common.core.utils.Json;
import com.jsbs.iam.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @ClassName: UserGroupManagerController
 * @Author: tenghuawei
 * @Date: 2023/1/5 15:12
 * @Description:
 */

@Slf4j
@RestController
@RequestMapping("/iam/auth/userGroupManager")
@SuppressWarnings("all")
public class IamStaticUserGroupManagerController extends BaseController{

    @Autowired
    IamStaticUserGroupManagerService iamStaticUserGroupManagerService;

    @Autowired
    IamRoleManagerService iamRoleManagerService;

    /**
     * 功能描述：新增静态用户组
     * @param iamStaticUserGroupAddDto
     * @return Result
     */
    @PostMapping("/createStaticUserGroup")
    public Result createStaticUserGroup (HttpServletRequest request, @RequestBody IamStaticUserGroupAddDto iamStaticUserGroupAddDto) {
        try {
            String adminRoleCode = request.getHeader(Constants.ADMIN_ROLE_CODE);
            if(StringUtils.isBlank(adminRoleCode)){
                return Result.failWithMsg("管理员角色编码不可为空！");
            }
            // 获取当前登录人
            String userCode = (String) request.getHeader(Constants.USER_CODE);
            //先使用伪数据
//            userCode="admin";
            if (StringUtils.isBlank(userCode)) {
                return Result.failWithMsg("当前登录状态异常！");
            }
            //归属租户
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
            if(StringUtils.isBlank(iamStaticUserGroupAddDto.getUserGroupName())){
              return Result.failWithMsg("用户组名称不可为空！");
            }
            // 普管角色编码
            iamStaticUserGroupAddDto.setAdminRoleCode(adminRoleCode);
            iamStaticUserGroupAddDto.setCreatepPerson(userCode);
            iamStaticUserGroupAddDto.setCompanyCode(companyCode);
            log.info("Route==>UserGroupManagerController method=>createStaticUserGroup 创建静态用户组入参：{}",Json.toJsonString(iamStaticUserGroupAddDto));
            int createStaticUserGroup = iamStaticUserGroupManagerService.createStaticUserGroup(iamStaticUserGroupAddDto);
            if(0 == createStaticUserGroup){
                return Result.failWithMsg("创建静态用户组失败！");
            }
            return Result.successWithMsg("创建静态用户组成功！");
        }catch (Exception e){
            log.error("Route=>UserGroupManagerController method=>createStaticUserGroup 创建静态用户组异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamStaticUserGroupAddDto));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：查询静态用户组
     * @param iamQueryStaticUserGroupParam
     * @return Result
     */
    @PostMapping("/queryUserGroup")
    public Result queryUserGroup (HttpServletRequest request, @RequestBody IamQueryStaticUserGroupParam iamQueryStaticUserGroupParam) {
    try {
        String adminRoleCode = request.getHeader(Constants.ADMIN_ROLE_CODE);
        if(StringUtils.isBlank(adminRoleCode)){
            return Result.failWithMsg("管理员角色编码不可为空！");
        }
        //归属租户
        String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
        //companyCpde先使用伪数据
//        companyCode="000001";
        if (StringUtils.isBlank(companyCode)) {
            return Result.failWithMsg("当前归属租户状态异常！");
        }
        iamQueryStaticUserGroupParam.setAdminRoleCode(adminRoleCode);
        iamQueryStaticUserGroupParam.setCompanyCode(companyCode);
        log.info("Route==>UserGroupManagerController method=>queryUserGroup 查询用户组入参：{}",Json.toJsonString(iamQueryStaticUserGroupParam));
        PageInfo<IamUserGroupVo> iamUserGroupVoPageInfo = iamStaticUserGroupManagerService.queryUserGroup(iamQueryStaticUserGroupParam);
        if(0==iamUserGroupVoPageInfo.getTotal()){
            return Result.failWithMsg("无数据");
        }
        return Result.success("查询用户组成功！",iamUserGroupVoPageInfo);
    }catch (Exception e){
        log.error("Route=>UserGroupManagerController method=>queryUserGroup 查询用户组异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamQueryStaticUserGroupParam));
        return handleException(e,e.getMessage());
    }
}


    /**
     * 功能描述：编辑静态用户组
     * @param iamStaticUserGroupEditDto
     * @return Result
     */
    @PostMapping("/userGroupEdit")
    public Result userGroupEdit(HttpServletRequest request, @RequestBody IamStaticUserGroupEditDto iamStaticUserGroupEditDto) {
        try {
            String adminRoleCode = request.getHeader(Constants.ADMIN_ROLE_CODE);
            if(StringUtils.isBlank(adminRoleCode)){
                return Result.failWithMsg("管理员角色编码不可为空！");
            }
            //  获取当前登录人
            String userCode = (String) request.getHeader(Constants.USER_CODE);
            //先使用伪数据
//            userCode="admin";
            if (StringUtils.isBlank(userCode)) {
                return Result.failWithMsg("当前登录状态异常！");
            }
            //归属租户
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
            if(StringUtils.isBlank(iamStaticUserGroupEditDto.getUserGroupCode())){
                return Result.failWithMsg("用户组编码不可为空！");
            }
            if(StringUtils.isBlank(iamStaticUserGroupEditDto.getUserGroupName()) || iamStaticUserGroupEditDto.getUserGroupName().length()>20){
                return Result.failWithMsg("用户组名称不可为空，且最长不超过20字！");
            }
            if(StringUtils.isNotBlank(iamStaticUserGroupEditDto.getUserGroupInfo()) && iamStaticUserGroupEditDto.getUserGroupInfo().length()>200){
                return Result.failWithMsg("用户组描述最长不超过200字！");
            }
            iamStaticUserGroupEditDto.setAdminRoleCode(adminRoleCode);
            iamStaticUserGroupEditDto.setUserName(userCode);
            iamStaticUserGroupEditDto.setCompanyCode(companyCode);
            log.info("Route==>UserGroupManagerController method=>userGroupEdit 编辑静态用户组入参：{}",Json.toJsonString(iamStaticUserGroupEditDto));
            if(0== iamStaticUserGroupManagerService.userGroupEdit(iamStaticUserGroupEditDto)){
                return Result.failWithMsg("编辑静态用户组失败！");
            }
            return Result.successWithMsg("编辑静态用户组成功！");
        }catch (Exception e){
            log.error("Route=>UserGroupManagerController method=>userGroupEdit 编辑静态用户组异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamStaticUserGroupEditDto));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：删除静态用户组
     * @param iamStaticUserGroupDeleteParam
     * @return Result
     */
    @PostMapping("/userGroupDelete")
    public Result userGroupDelete(HttpServletRequest request,@RequestBody IamStaticUserGroupDeleteParam iamStaticUserGroupDeleteParam) {
        try {
            String adminRoleCode = request.getHeader(Constants.ADMIN_ROLE_CODE);
            if(StringUtils.isBlank(adminRoleCode)){
                return Result.failWithMsg("管理员角色编码不可为空！");
            }
            //归属租户
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
            if(StringUtils.isBlank(iamStaticUserGroupDeleteParam.getUserGroupCode())){
                return Result.failWithMsg("静态用户组编码不可为空，请选择一个静态用户组删除！");
            }
            iamStaticUserGroupDeleteParam.setAdminRoleCode(adminRoleCode);
            iamStaticUserGroupDeleteParam.setCompanyCode(companyCode);
            log.info("Route=>UserGroupManagerController method=>userGroupDelete 删除静态用户组入参：{}",Json.toJsonString(iamStaticUserGroupDeleteParam));
            iamStaticUserGroupManagerService.userGroupDelete(iamStaticUserGroupDeleteParam);
            return Result.successWithMsg("删除静态用户组成功！");
        }catch (Exception e){
            log.error("Route=>UserGroupManagerController method=>userGroupDelete 删除静态用户组异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamStaticUserGroupDeleteParam));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：选择一个静态用户组，查询用户（该静态用户组下的用户，分页展示）
     * @param iamQueryStaticUserGroupUsersParam
     * @return Result
     */
    @PostMapping("/queryUserGroupUsers")
    public Result queryUserGroupUsers(@RequestBody IamQueryStaticUserGroupUsersParam iamQueryStaticUserGroupUsersParam) {
        try {
            if(StringUtils.isBlank(iamQueryStaticUserGroupUsersParam.getUserGroupCode())){
                return Result.failWithMsg("静态用户组编码不可为空！");
            }
            log.info("Route=>UserGroupManagerController method=>queryUserGroupUsers 查询静态用户组下的用户入参为：{}", Json.toJsonString(iamQueryStaticUserGroupUsersParam));
            PageInfo<IamUserInfoVo> pageInfo = iamStaticUserGroupManagerService.queryUserGroupUsers(iamQueryStaticUserGroupUsersParam);
            if(0==pageInfo.getTotal()){
                return Result.failWithMsg("无数据");
            }
            return Result.success("查询静态用户组下的用户信息成功！",pageInfo);
        }catch (Exception e){
            log.error("Route=>UserGroupManagerController method=>queryUserGroupUsers 查询静态用户组下的用户异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamQueryStaticUserGroupUsersParam));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：某个静态用户组下可以新增的用户（分页展示）
     * @param iamQueryStaticUserGroupUsersParam
     * @return Result
     */
    @PostMapping("/queryUserGroupNotUsers")
    public Result queryUserGroupNotUsers(@RequestBody IamQueryStaticUserGroupUsersParam iamQueryStaticUserGroupUsersParam) {
        try {
            if(StringUtils.isBlank(iamQueryStaticUserGroupUsersParam.getUserGroupCode())){
                return Result.failWithMsg("静态用户组编码不可为空！");
            }
            log.info("Route=>UserGroupManagerController method=>queryUserGroupUsers 查询静态用户组下可以新增的用户入参为：{}", Json.toJsonString(iamQueryStaticUserGroupUsersParam));
            PageInfo<IamUserInfoVo> pageInfo = iamStaticUserGroupManagerService.queryUserGroupNotUsers(iamQueryStaticUserGroupUsersParam);
            return Result.success("查询该静态用户组下的可以新增的用户成功！",pageInfo);
        }catch (Exception e){
            log.error("Route=>UserGroupManagerController method=>queryUserGroupNotUsers 查询该静态用户组下的可以新增的用户异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamQueryStaticUserGroupUsersParam));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：某个静态用户组下新增用户
     * @param iamStaticUserGroupUsersAddDto
     * @return Result
     */
    @PostMapping("/userGroupUserAdd")
    public Result userGroupUserAdd(HttpServletRequest request, @RequestBody IamStaticUserGroupUsersAddDto iamStaticUserGroupUsersAddDto) {
        try {
            // 获取当前登录人
//            String userName = (String) request.getSession().getAttribute("userName");
            String userCode = (String) request.getHeader(Constants.USER_CODE);
            //先使用伪数据
//            userName="admin";
            if (StringUtils.isBlank(userCode)) {
                return Result.failWithMsg("当前登录状态异常！");
            }
            //归属租户
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }

            if(StringUtils.isBlank(iamStaticUserGroupUsersAddDto.getUserGroupCode())){
                return Result.failWithMsg("静态用户组编码不可为空！");
            }
            iamStaticUserGroupUsersAddDto.setCompanyCode(companyCode);
            iamStaticUserGroupUsersAddDto.setCreatepPerson(userCode);
            log.info("Route=>UserGroupManagerController method=>userGroupUserAdd 该静态用户组下新增用户的入参为：{}", Json.toJsonString(iamStaticUserGroupUsersAddDto));
            iamStaticUserGroupManagerService.userGroupUserAdd(iamStaticUserGroupUsersAddDto);
            return Result.successWithMsg("该静态用户组下新增用户成功！");
        }catch (Exception e){
            log.error("Route=>UserGroupManagerController method=>userGroupUserAdd 该静态用户组下新增用户异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamStaticUserGroupUsersAddDto));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：某个静态用户组下移除用户
     * @param iamStaticUserGroupUsersRemoveDto
     * @return Result
     */
    @PostMapping("/userGroupUsersRemove")
    public Result userGroupUsersRemove(@RequestBody IamStaticUserGroupUsersRemoveDto iamStaticUserGroupUsersRemoveDto) {
        try {
            if(StringUtils.isBlank(iamStaticUserGroupUsersRemoveDto.getUserGroupCode())){
                return Result.failWithMsg("静态用户组编码不可为空！");
            }
            if(CollectionUtils.isEmpty(iamStaticUserGroupUsersRemoveDto.getUserCodes())){
                return Result.failWithMsg("请至少勾选一条用户进行移除！");
            }
            log.info("Route=>UserGroupManagerController method=>userGroupUsersRemove 该静态用户组下移除用户的入参为：{}", Json.toJsonString(iamStaticUserGroupUsersRemoveDto));
            int usersRemove = iamStaticUserGroupManagerService.userGroupUsersRemove(iamStaticUserGroupUsersRemoveDto);
            return Result.successWithMsg("该静态用户组下移除用户成功！移除用户数："+usersRemove);
        }catch (Exception e){
            log.error("Route=>UserGroupManagerController method=>userGroupUsersRemove 该静态用户组下移除用户异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamStaticUserGroupUsersRemoveDto));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：查询当前普管用户的1个应用类型下的权限范围内的应用的菜单（按钮）树
     * @param iamMenuManagerSelectDto
     * @return Result
     */
    @PostMapping("/getMenuThreeInfo")
    public Result getMenuThreeInfo(HttpServletRequest request) {
        try {
            IamMenuManagerSelectDto iamMenuManagerSelectDto = new IamMenuManagerSelectDto();
            //归属租户
            String companyCode = request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
            // 应用菜单树包含菜单+按钮
            iamMenuManagerSelectDto.setIncludeButton(Boolean.TRUE);

            // 当前普管用户的所属的 管理员角色编码
            String adminRoleCode = request.getHeader(Constants.ADMIN_ROLE_CODE);
            // 测试使用的普管角色伪数据
//            adminRoleCode="JS0004";
            // 查询该普管用户的 组织范围权限列表 + 应用范围权限列表
            Result result = iamRoleManagerService.queryAdminRole(adminRoleCode, companyCode);
            AdminRoleVo adminRoleVo = JSONObject.parseObject(Json.toJsonString(result.getData()),AdminRoleVo.class);
            // 查询管理员应用范围权限列表
            List<IamAdminRoleApplyInfoVo> applyRoleList = adminRoleVo.getApplyRoleList();
            ArrayList<Object> list = new ArrayList<>();
            // 该普管权限范围下的菜单（按钮）树
            applyRoleList.forEach(apply->{
                iamMenuManagerSelectDto.setApplyCode(apply.getApplyCode());
                log.info("Route=>UserGroupManagerController method=>getMenuThreeInfo 查询应用类型下的菜单树入参：{}", Json.toJsonString(iamMenuManagerSelectDto));
                List<MenuThreeVo> menuThreeInfo = iamStaticUserGroupManagerService.getMenuThreeInfo(iamMenuManagerSelectDto);
                list.addAll(menuThreeInfo);
            });
            return Result.success("查询应用类型下的菜单树成功！",list);
        }catch (Exception e){
            log.error("Route=>UserGroupManagerController method=>getMenuThreeInfo 查询应用类型下的菜单树异常：{},入参为：{}", e.getMessage());
            return handleException(e,e.getMessage());
        }
    }
    /**
     * 功能描述：获取某个静、动态用户组下某个菜单树下已经勾选的菜单或按钮，回填
     * @param iamMenuManagerAlreadySelectDto
     * @return Result
     */
    @PostMapping("/getAlreadyMenuThreeInfo")
    public Result getAlreadyMenuThreeInfo(HttpServletRequest request,@RequestBody IamMenuManagerAlreadySelectDto iamMenuManagerAlreadySelectDto) {
        try {
            //归属租户
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
            if(Objects.isNull(iamMenuManagerAlreadySelectDto.getUserGroupCode())){
                return Result.failWithMsg("用户组编码不可为空！");
            }
            if(CollectionUtils.isEmpty(iamMenuManagerAlreadySelectDto.getApplyCodes())){
                return Result.failWithMsg("应用编码不可为空！");
            }
            iamMenuManagerAlreadySelectDto.setCompanyCode(companyCode);
            log.info("Route=>UserGroupManagerController method=>getAlreadyMenuThreeInfo 查询应用类型下的菜单树入参：{}", Json.toJsonString(iamMenuManagerAlreadySelectDto));
            Set<String> alreadyMenuThreeInfo = iamStaticUserGroupManagerService.getAlreadyMenuThreeInfo(iamMenuManagerAlreadySelectDto);
            return Result.success("查询该用户组下菜单树中已经勾选的菜单或按钮成功！",alreadyMenuThreeInfo);
        }catch (Exception e){
            log.error("Route=>UserGroupManagerController method=>getAlreadyMenuThreeInfo 查询应用类型下的菜单树异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamMenuManagerAlreadySelectDto));
            return handleException(e,e.getMessage());
        }
    }

    /**
     * 功能描述：动、静态用户组权限编辑
     * @param iamStaticUserGroupUsersPermissionDto
     * @return Result
     */
    @PostMapping("/staticUserGroupPermissionEdit")
    public Result staticUserGroupPermissionEdit(HttpServletRequest request,@RequestBody IamStaticUserGroupUsersPermissionDto iamStaticUserGroupUsersPermissionDto) {
        try {
            // 获取当前登录人
            String userName = (String) request.getHeader(Constants.NAME);
            //先使用伪数据
//            userName="admin";
            if (StringUtils.isBlank(userName)) {
                return Result.failWithMsg("当前登录状态异常！");
            }
            //归属租户
            String companyCode = (String) request.getHeader(Constants.COMPANY_CODE);
            //companyCpde先使用伪数据
//            companyCode="000001";
            if (StringUtils.isBlank(companyCode)) {
                return Result.failWithMsg("当前归属租户状态异常！");
            }
            if(StringUtils.isBlank(iamStaticUserGroupUsersPermissionDto.getUserGroupCode())){
                return Result.failWithMsg("用户组编码不可为空！");
            }
            iamStaticUserGroupUsersPermissionDto.setCreatePerson(userName);
            iamStaticUserGroupUsersPermissionDto.setCompanyCode(companyCode);
            log.info("Route=>UserGroupManagerController method=>staticUserGroupPermissionEdit 用户组权限编辑的入参为：{}", Json.toJsonString(iamStaticUserGroupUsersPermissionDto));
            iamStaticUserGroupUsersPermissionDto.getIamStaticUserGroupUsersPermissionEditingDtos().forEach(item->{
                BeanUtils.copyProperties(iamStaticUserGroupUsersPermissionDto,item);
                if(Objects.isNull(item.getApplyCode())) {
                    throw new RuntimeException("应用编码不可为空！");
                }
                if(CollectionUtils.isEmpty(item.getMenuThreeVos())) {
                    log.warn("没有勾选应用下的任何菜单或按钮！");
                }
                iamStaticUserGroupManagerService.staticUserGroupPermissionEdit(item);
            });
            return Result.successWithMsg("用户组权限编辑成功！");
        }catch (Exception e){
            log.error("Route=>UserGroupManagerController method=>staticUserGroupPermissionEdit 用户组权限编辑异常：{},入参为：{}", e.getMessage(), Json.toJsonString(iamStaticUserGroupUsersPermissionDto));
            return handleException(e,e.getMessage());
        }
    }


}
